import {listType, addType, updateType, removeType} from '_api/projects/type'
import {_Promise} from "_libs/util";
import Vue from "vue";

export default {
  namespaced: true,
  state: {
    typeList: []
  },
  mutations: {
    setTypeList(state, typeList) {
      state.typeList = typeList
    },
    addType(state, type) {
      state.typeList.unshift(type);
    },
    updateType(state, type) {
      for (let i = 0; i < state.typeList.length; i++) {
        let existsType = state.typeList[i];
        if (existsType.id === type.id) {
          let keys = Object.keys(type);
          keys.forEach(key => {
            Vue.set(state.typeList[i], key, type[key])
          })
          break
        }
      }
    },
    removeType(state, type) {
      state.typeList = state.typeList.filter(existsType => {
        if (existsType.id !== type.id) {
          return existsType;
        }
      })
    }
  },
  actions: {
    // 获取所有项目类型
    listType({state, commit}) {
      return _Promise(listType(), res => {
        commit('setTypeList', res.data)
      })
    },

    // 添加项目类型
    addType({state, commit}, type) {
      return _Promise(addType(type), res => {
        commit('addType', res.data)
      })
    },

    // 更新项目类型
    updateType({state, commit}, type) {
      return _Promise(updateType(type), res => {
        commit('updateType', res.data)
      })
    },

    // 删除项目类型
    removeType({state, commit}, type) {
      return _Promise(removeType(type.id), res => {
        commit('removeType', type)
      })
    }
  }
}
